﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AdBlockListToTPLConverter;
using System.IO;
using System.Net;

namespace adblock2tplWebConverter
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                RadioButtonList1.SelectedIndex = 0;
            MultiView1.ActiveViewIndex = RadioButtonList1.SelectedIndex;
            LabelError.Text = "";
        }

        protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = RadioButtonList1.SelectedIndex;
        }

        protected void ButtonConvertFromFile_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                Response.ContentType = "text/plain";
                Response.Clear();

                string convertedFileName = Path.GetFileNameWithoutExtension(FileUpload1.FileName) + "_tpl.txt";

                Response.AppendHeader("Content-Disposition", "attachment; filename=" + convertedFileName);
                Response.BufferOutput = true;

                AdBlockConverter.Convert(FileUpload1.FileContent, Response.OutputStream);

                Response.End();

            }
        }

        protected void ButtonConvertFromURL_Click(object sender, EventArgs e)
        {
            string url = TextBoxAdBlockFilterURL.Text.Trim();

            if (string.IsNullOrEmpty(url))
                return;
            if (!url.StartsWith("http"))
                url = "http://" + url;

            try
            {
                WebClient webClient = new WebClient();
                Stream urlFileStream = webClient.OpenRead(url);

                Response.ContentType = "text/plain";
                Response.Clear();

                string convertedFileName = Path.GetFileNameWithoutExtension(url) + "_tpl.txt";

                Response.AppendHeader("Content-Disposition", "attachment; filename=" + convertedFileName);
                Response.BufferOutput = true;

                AdBlockConverter.Convert(urlFileStream, Response.OutputStream);

                urlFileStream.Close();
                Response.End();
            }
            catch(Exception)
            {
                LabelError.Text = "Wystąpił błąd, sprawdź czy podany URL jest poprawny";
            }
        }
    }
}